package com.heima.comment.service.impl;

import com.heima.aliyun.GreenTextScan;
import com.heima.comment.service.ICommentReplyService;
import com.heima.feign.clients.UserClient;
import com.heima.model.comment.dtos.CommentReplyLikeDTO;
import com.heima.model.comment.dtos.CommentReplyQueryDTO;
import com.heima.model.comment.dtos.CommentReplySaveDTO;
import com.heima.model.comment.dtos.CommentSaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentReply;
import com.heima.model.comment.pojos.ApCommentReplyLike;
import com.heima.model.comment.vos.ApCommentReplyVO;
import com.heima.model.comment.vos.ApCommentVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentReplyService implements ICommentReplyService {

    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private UserClient userClient;
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * APP 端-文章详情页-发表文章评论回复
     * @param commentReplySaveDTO
     * @return
     */
    @Override
    public ResponseResult saveCommentReply(CommentReplySaveDTO commentReplySaveDTO) {
        //1.校验参数
        Integer loginId = AppThreadLocalUtils.getUser();
        if(loginId == null || loginId.intValue() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.保存文章评论回复数据
            //2.1对评论回复内容进行安全检查
        commentContentScan(commentReplySaveDTO);
            //2.2查询发表评论回复的用户信息
        ResponseResult<ApUser> userResult = userClient.findUserById(loginId);
        if(userResult.getCode().intValue() != 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.REMOTE_SERVER_ERROR, userResult.getErrorMessage());
        }
        ApUser apUser = userResult.getData();
        if(apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "当前发表评论回复用户的信息不存在,请联系管理员");
        }
        ApCommentReply apCommentReply = new ApCommentReply();
        apCommentReply.setAuthorId(apUser.getId());
        apCommentReply.setAuthorName(apUser.getName());
        apCommentReply.setCommentId(commentReplySaveDTO.getCommentId());
        apCommentReply.setContent(commentReplySaveDTO.getContent());
        apCommentReply.setLikes(0);
        //apCommentReply.setLongitude();
        //apCommentReply.setLatitude();
        //apCommentReply.setAddress();
        apCommentReply.setCreatedTime(new Date());
        apCommentReply.setUpdatedTime(new Date());
        mongoTemplate.save(apCommentReply);
        //3.修改文章评论的回复数
        ApComment apComment = mongoTemplate.findById(commentReplySaveDTO.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);
        //4.返回响应
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult handleLike(CommentReplyLikeDTO commentReplyLikeDTO) {
        //1.校验参数
        //1.1校验登陆状态
        Integer loginId = AppThreadLocalUtils.getUser();
        if(loginId == null || loginId.intValue() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //1.2检查点赞的评论回复是否存在
        ApCommentReply apCommentReply = mongoTemplate.findOne(Query.query(Criteria.where("id").is(commentReplyLikeDTO.getCommentReplyId())), ApCommentReply.class);
        if(apCommentReply == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "点赞的评论不存在");
        }
        //1.3检查是否重复点赞
        ApCommentReplyLike apCommentReplyLike = mongoTemplate.findOne(Query.query(Criteria.where("author_id").is(loginId).and("comment_reply_id").is(commentReplyLikeDTO.getCommentReplyId())), ApCommentReplyLike.class);
        if(apCommentReplyLike != null && commentReplyLikeDTO.getOperation().intValue() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW, "已经点过赞，请勿重复点赞");
        }
        //2.处理文章评论点赞或取消点赞
        if(commentReplyLikeDTO.getOperation().intValue() == 0){
            //点赞
            apCommentReply.setLikes(apCommentReply.getLikes() + 1);
            mongoTemplate.save(apCommentReply);

            apCommentReplyLike = new ApCommentReplyLike();
            apCommentReplyLike.setAuthorId(loginId);
            apCommentReplyLike.setCommentReplyId(apCommentReply.getId());
            apCommentReplyLike.setOperation(commentReplyLikeDTO.getOperation());
            mongoTemplate.save(apCommentReplyLike);
        }else {
            //取消点赞
            apCommentReply.setLikes(apCommentReply.getLikes() - 1 < 0 ? 0 : apCommentReply.getLikes() - 1);
            mongoTemplate.save(apCommentReply);

            mongoTemplate.remove(Query.query(Criteria.where("author_id").is(loginId).and("comment_reply_id").is(commentReplyLikeDTO.getCommentReplyId())), ApCommentReplyLike.class);
        }
        //3.响应结果
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("likes", apCommentReply.getLikes());
        return ResponseResult.okResult(resultMap);
    }

    @Override
    public ResponseResult listCommentReply(CommentReplyQueryDTO commentReplyQueryDTO) {
        //1.校验参数
        //1.1校验分页参数
        if(commentReplyQueryDTO.getSize() == null || commentReplyQueryDTO.getSize().intValue() <= 0){
            commentReplyQueryDTO.setSize(10);    //默认每页展示 10 条评论
        }
        //2.分页查询文章评论回复列表
        Query query = Query.query(Criteria.where("comment_id").is(commentReplyQueryDTO.getCommentId()).and("created_time").lt(commentReplyQueryDTO.getMinDate())).limit(commentReplyQueryDTO.getSize()).with(Sort.by(Sort.Direction.DESC, "created_time"));
        List<ApCommentReply> apCommentReplyList = mongoTemplate.find(query, ApCommentReply.class);
        //3.返回响应
        //3.1用户未登录，直接返回评论列表
        Integer loginId = AppThreadLocalUtils.getUser();
        if(loginId == null || loginId.intValue() == 0){
            return ResponseResult.okResult(apCommentReplyList);
        }
        //3.2用户已登录,对当前用户点赞过的评论回复进行特殊处理
        ArrayList<ApCommentReplyVO> apCommentReplyVOList = new ArrayList<>();
        //3.2.1获取待展示评论列表的所有评论回复的 id 集合
        List<String> apCommentReplyIdList = apCommentReplyList.stream().map(apCommentReply -> apCommentReply.getId()).collect(Collectors.toList());
        //3.2.2获取当前用户点赞过的评论回复列表
        List<ApCommentReplyLike> apCommentReplyLikes = mongoTemplate.find(Query.query(Criteria.where("author_id").is(loginId).and("comment_reply_id").in(apCommentReplyIdList)), ApCommentReplyLike.class);
        //3.2.3封装 ApComment 为 ApCommentVO
        if(!CollectionUtils.isEmpty(apCommentReplyList) && !CollectionUtils.isEmpty(apCommentReplyLikes)){
            apCommentReplyList.stream().forEach(apCommentReply -> {
                ApCommentReplyVO apCommentReplyVO = new ApCommentReplyVO();
                BeanUtils.copyProperties(apCommentReply,apCommentReplyVO);
                apCommentReplyLikes.stream().forEach(apCommentReplyLike -> {
                    if(apCommentReplyLike.getCommentReplyId().equals(apCommentReply.getId())){
                        apCommentReplyVO.setOperation((short) 0);
                    }
                });
                apCommentReplyVOList.add(apCommentReplyVO);
            });
            return ResponseResult.okResult(apCommentReplyVOList);
        }
        return ResponseResult.okResult(apCommentReplyList);
    }

    /**
     * 接入阿里云内容安全检测
     * @param commentReplySaveDTO
     */
    private void commentContentScan(CommentReplySaveDTO commentReplySaveDTO) {
        try {
            Map resultMap = greenTextScan.greenTextScan(commentReplySaveDTO.getContent());
            if("block".equalsIgnoreCase((String) resultMap.get("suggestion")) || "review".equalsIgnoreCase((String) resultMap.get("suggestion"))){
                String filteredContent = (String) resultMap.get("filteredContent");
                //将原始敏感评论替换为敏感词被屏蔽后的内容
                commentReplySaveDTO.setContent(filteredContent);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("接入阿里云文本内容审核失败，失败原因: {}", e.getMessage());
        }
    }
}
